﻿// ***********************************************************************
// Assembly         : GooglePredict
// Author           : aj
// Created          : 10-08-2010
//
// Last Modified By : aj
// Last Modified On : 10-08-2010
// Description      : 
//
//
// ***********************************************************************

namespace Google.API.Predict.Auth
{
    using System.Globalization;
    using System.IO;
    using System.Net;

    /// <summary>
    /// Retrieves authorization token for use with Google Predict
    /// http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html
    /// </summary>
    public class ClientLoginRequest
    {
        /// <summary>
        /// Authentication URL for CLientLogin
        /// </summary>
        public const string AuthenticationUrl = "https://www.google.com/accounts/ClientLogin";

        /// <summary>
        /// Authentication URL for string formatting
        /// </summary>
        private const string AuthenticationUrlFormat = "{0}?accountType=HOSTED_OR_GOOGLE&service=xapi&source=account&Email={1}&Passwd={2}";

        /// <summary>
        /// ContentType header of Request
        /// </summary>
        private const string ContentType = "application/x-www-form-urlencoded";

        /// <summary>
        /// HTTP Request method to use
        /// </summary>
        private const string Method = "POST";

        /// <summary>
        /// Initiates a ClientLogin request and attempts to retrieve SID, LSID and Auth
        /// </summary>
        /// <param name="login">Google Email Address</param>
        /// <param name="password">Google Password</param>
        /// <returns>Client Login Response object</returns>
        internal static ClientLoginResponse Authenticate(string login, string password)
        {
            var requestUrl = string.Format(CultureInfo.CurrentCulture, AuthenticationUrlFormat, AuthenticationUrl, login, System.Web.HttpUtility.UrlEncode(password));

            // CREATE REQUEST
            var request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.ContentType = ContentType;
            request.Method = Method;
            request.ContentLength = 0;

            HttpWebResponse response;
            try
            {
                response = request.GetResponse() as HttpWebResponse;

                string rawResponse;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    rawResponse = reader.ReadToEnd();
                }

                return new ClientLoginResponse(rawResponse);
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;                

                var responseMsg = response != null ? new StreamReader(response.GetResponseStream()).ReadToEnd() : string.Empty;
                var loginResponse = new ClientLoginResponse(responseMsg)
                                        {
                                            InnerException = e
                                        };

                if (response != null)
                {
                    loginResponse.ResponseStatusCode = response.StatusCode;
                    loginResponse.ResponseStatusCodeDescription = response.StatusDescription;
                }

                return loginResponse;
            }
        }
    }
}